package q19_removeNthFromEnd;

public class Solution_1 {

    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {

        if(n == 1 && head.next == null){
            return null;
        }

        n = countList(head) - n + 1;

        if(n == 1){
            head = head.next;
            return head;
        }

        ListNode newListNode = head;
        for (int i = 0; i < n - 2; i++) { // 找第n-1个节点，要用n-2
            head = head.next;
        }
        if(head.next.next == null){
            head.next = null;
            return newListNode;
        }else {
            head.next = head.next.next;
            return newListNode;
        }

    }

    public static int countList(ListNode head){
        int count = 0;
        while(head != null){
            head = head.next;
            count++;
        }
        return count;
    }
}
